<template>
  <MainLayout>
    <div class="group-manage-page">
      <!-- 页面标题 -->
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold">分组管理</h2>
        <n-button 
          type="primary" 
          @click="showCreateGroupDialog = true"
        >
          <template #icon>
            <n-icon size="18">
              <AddOutline />
            </n-icon>
          </template>
          添加分组
        </n-button>
      </div>
      
      <!-- 分组列表 -->
      <div v-if="isLoading" class="flex justify-center items-center py-12">
        <n-spin size="large" />
      </div>
      
      <div v-else-if="groups.length === 0" class="text-center py-12">
        <n-empty description="暂无任务分组">
          <template #icon>
            <n-icon size="48">
              <ListOutline />
            </n-icon>
          </template>
          <n-button type="primary" @click="showCreateGroupDialog = true">
            创建第一个分组
          </n-button>
        </n-empty>
      </div>
      
      <div v-else>
        <n-table 
          :data="groups" 
          :columns="columns" 
          :pagination="false"
          bordered
          class="mb-6"
        >
          <template #body-cell-name="{ row }">
            <div class="flex items-center">
              {{ row.name }}
              <n-tag 
                v-if="row.is_default" 
                type="info" 
                size="small" 
                class="ml-2"
              >
                默认
              </n-tag>
            </div>
          </template>
          <template #body-cell-task_count="{ row }">
            <n-badge :value="row.task_count || 0" type="info" />
          </template>
          <template #body-cell-actions="{ row }">
            <div class="flex space-x-2">
              <n-button 
                text 
                type="primary" 
                size="small" 
                @click="editGroup(row)"
                :disabled="row.is_default"
              >
                <template #icon>
                  <n-icon size="16">
                    <CreateOutline />
                  </n-icon>
                </template>
                编辑
              </n-button>
              <n-button 
                text 
                type="error" 
                size="small" 
                @click="showDeleteConfirm(row)"
                :disabled="row.is_default"
              >
                <template #icon>
                  <n-icon size="16">
                    <TrashOutline />
                  </n-icon>
                </template>
                删除
              </n-button>
            </div>
          </template>
        </n-table>
      </div>
      
      <!-- 创建分组对话框 -->
      <n-dialog v-model:show="showCreateGroupDialog" title="创建分组">
        <n-form 
          :model="groupForm" 
          :rules="groupRules"
          ref="groupFormRef"
        >
          <n-form-item path="name">
            <n-input 
              v-model:value="groupForm.name" 
              placeholder="请输入分组名称"
              autofocus
            />
          </n-form-item>
        </n-form>
        <template #footer>
          <div class="flex justify-end space-x-2">
            <n-button @click="resetForm">取消</n-button>
            <n-button 
              type="primary" 
              @click="submitForm"
              :loading="isSubmitting"
            >
              {{ editingGroup ? '保存修改' : '创建分组' }}
            </n-button>
          </div>
        </template>
      </n-dialog>
      
      <!-- 删除确认对话框 -->
      <n-dialog 
        v-model:show="showDeleteDialog" 
        title="确认删除" 
        type="warning"
      >
        <div class="text-center py-4">
          <n-icon size="48" type="error" class="mb-4" />
          <p class="mb-4">您确定要删除分组 "{{ deletingGroup?.name }}" 吗？</p>
          <p class="text-gray-500 dark:text-gray-400">
            此操作不可恢复，该分组下的所有任务将被移至默认分组。
          </p>
        </div>
        <template #footer>
          <div class="flex justify-end space-x-2">
            <n-button @click="showDeleteDialog = false">取消</n-button>
            <n-button 
              type="error" 
              @click="deleteGroup"
              :loading="isDeleting"
            >
              确认删除
            </n-button>
          </div>
        </template>
      </n-dialog>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import MainLayout from '@/layouts/MainLayout.vue'
import { useGroupStore } from '@/store/group'
import { Group, CreateGroupRequest, UpdateGroupRequest } from '@/types'
import { 
  AddOutline, 
  ListOutline, 
  CreateOutline, 
  TrashOutline
} from '@vicons/ionicons5'
import type { FormInstance } from 'naive-ui'

// 状态
const showCreateGroupDialog = ref<boolean>(false)
const showDeleteDialog = ref<boolean>(false)
const isSubmitting = ref<boolean>(false)
const isDeleting = ref<boolean>(false)
const groupFormRef = ref<FormInstance | null>(null)
const editingGroup = ref<Group | null>(null)
const deletingGroup = ref<Group | null>(null)

// 分组表单
const groupForm = reactive<CreateGroupRequest>({
  name: ''
})

// 分组表单规则
const groupRules = {
  name: [
    { required: true, message: '请输入分组名称', trigger: 'blur' },
    { min: 1, max: 20, message: '分组名称长度在 1 到 20 个字符', trigger: 'blur' }
  ]
}

// 获取分组store
const groupStore = useGroupStore()

// 从store获取数据
const groups = computed(() => groupStore.groups)
const isLoading = computed(() => groupStore.isLoading)

// 表格列配置
const columns = [
  {
    title: '分组名称',
    key: 'name'
  },
  {
    title: '任务数量',
    key: 'task_count'
  },
  {
    title: '创建时间',
    key: 'created_at',
    render: (row: Group) => {
      return new Date(row.created_at).toLocaleString()
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    fixed: 'right'
  }
]

// 重置表单
const resetForm = () => {
  groupForm.name = ''
  editingGroup.value = null
  groupFormRef.value?.restoreValidation()
  showCreateGroupDialog.value = false
}

// 提交表单
const submitForm = async () => {
  if (!groupFormRef.value) return
  
  try {
    await groupFormRef.value.validate()
    isSubmitting.value = true
    
    if (editingGroup.value) {
      // 更新分组
      await groupStore.updateGroup(editingGroup.value.group_id, groupForm as UpdateGroupRequest)
    } else {
      // 创建分组
      await groupStore.createGroup(groupForm)
    }
    
    resetForm()
  } catch (error) {
    console.error('操作失败:', error)
  } finally {
    isSubmitting.value = false
  }
}

// 编辑分组
const editGroup = (group: Group) => {
  editingGroup.value = group
  groupForm.name = group.name
  showCreateGroupDialog.value = true
}

// 显示删除确认
const showDeleteConfirm = (group: Group) => {
  deletingGroup.value = group
  showDeleteDialog.value = true
}

// 删除分组
const deleteGroup = async () => {
  if (!deletingGroup.value) return
  
  try {
    isDeleting.value = true
    await groupStore.deleteGroup(deletingGroup.value.group_id)
    showDeleteDialog.value = false
    deletingGroup.value = null
  } catch (error) {
    console.error('删除分组失败:', error)
  } finally {
    isDeleting.value = false
  }
}

// 页面加载时获取数据
onMounted(async () => {
  // 获取分组列表
  await groupStore.fetchGroups()
})
</script>

<style scoped>
.group-manage-page {
  max-width: 1200px;
  margin: 0 auto;
}
</style>